package com.jumper.property.comparer.util;

import com.alibaba.fastjson.JSON;
import com.jumper.property.comparer.convert.PropertyConverter;
import com.jumper.property.comparer.convert.PropertyConvertFactory;
import com.jumper.property.comparer.core.constant.ValueConstant;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;

/**
 * 工具类
 */
@Slf4j
public class ValueUtil {

    /**
     * 获取一个对象的值转字符串
     */
    public static String getStrValue(Object value, Field field) {
        value = getValue(value, field);
        if (value == null) {
            return ValueConstant.EMPTY_VALUE_STR;
        } else {
            return JSON.toJSONString(value);
        }
    }

    /**
     * 获取一个对象的属性值
     */
    public static Object getValue(Object value, Field field) {
        Object object = null;
        if (value != null) {
            try {
                field.setAccessible(true);
                object = convert(field.get(value), field);
            } catch (Exception e) {
                log.warn("获取对象属性值异常：{},属性：{}", JSON.toJSONString(value), field.getName(), e);
            }
        }
        return object;
    }

    /**
     * 格式转换
     */
    private static Object convert(Object object, Field field) {
        PropertyConverter converter = PropertyConvertFactory.getConverter(field.getType());
        if (converter == null) {
            return object;
        }
        return converter.convert(object, field);
    }
}
